package com.hue.gulimailcart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hue.common.constant.CartConstant;
import com.hue.common.utils.R;
import com.hue.gulimailcart.feign.ProductFeignService;
import com.hue.gulimailcart.service.ItemService;
import com.hue.gulimailcart.vo.CartItem;
import com.hue.gulimailcart.vo.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 姚凤桥
 * @Date: 2021/12/25 15:32
 * @Description:
 */
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public List<CartItem> getByMemberId(Long memberId) {
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_PREFIX + memberId);
        List<Object> itemObjs = cartOps.values();

        List<CartItem> items = itemObjs.stream()
                .map(itemObj -> {
                    CartItem cartItem = JSON.parseObject((String) itemObj, CartItem.class);

                    //远程查询商品最新的价格
                    R r = productFeignService.info(cartItem.getSkuId());
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    cartItem.setPrice(skuInfo.getPrice());

                    return cartItem;
                })
                .filter(CartItem::getCheck)
                .collect(Collectors.toList());

        return items;
    }
}
